package com.wan.util;

import cn.hutool.core.convert.Convert;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

public class ClassUtil {
    /**
     * 获取所有属性，可递归查找父类属性
     */
    public static List<Field> getAllFields(Class<?> clz,boolean recursionSuper, Predicate<Field> filter) {
        if (clz == null || clz == Object.class)
            return Collections.emptyList();
        List<Field> list = new ArrayList<>();
        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            if (filter != null && !filter.test(field)) {
                continue;
            }
            list.add(field);
        }
        if (recursionSuper)
            list.addAll(getAllFields( clz.getSuperclass(),true, filter));
        return list;
    }

    public static List<Field> getFieldsNoStatic(Class<?> clz) {
        return getAllFields(clz, true, field -> !Modifier.isStatic(field.getModifiers()));
    }


    public static List<Field> getAllFields(Class<?> clz,boolean recursionSuper) {
        return getAllFields(clz,recursionSuper, null);
    }

    /**
     * 校验对象数组类型匹配
     * @param objs 对象数组
     * @param types 指定类型数组
     * @return 是否相同
     */
    public static boolean checkObjectArrayEqualType(Object[] objs,Class<?>[] types){
        if (objs == null) {
            return types == null || types.length == 0;
        }

        if (types == null) {
            return objs.length == 0;
        }

        if (objs.length != types.length) {
            return false;
        }

        for (int i = 0; i < objs.length; i++) {
            //将2者都转换为包装类比较，防止int和integer类型匹配不上
            Class<?> objClass = Convert.wrap(objs[i].getClass());
            Class<?> typeClass = Convert.wrap(types[i]);
            if(objClass != typeClass && !typeClass.isAssignableFrom(objClass)){
                return false;
            }
        }
        return true;
    }

}
